extends "res://tanks/Tank.gd"

onready var parent = get_parent()

export (float) var turret_speed = 0.1
export (int) var detect_radius = 400
export (bool) var ignore_obstacle = false

var target :Node2D = null
var speed: float = 0.0

#需要注意一点的是，像_ready这类Node的虚函数是多级调用的，每一个脚本的这类函数都会分别被godot调用。
#因此，即使你覆盖了_ready（）,父脚本的_ready（）依然会执行
#解决方法是在父脚本的_ready中只调用ready函数，然后在子类中就可以通过覆盖ready函数来间接改变_ready函数的行为
func _ready():
	$DetectRadius/CollisionShape2D.shape = CircleShape2D.new()
	$DetectRadius/CollisionShape2D.shape.radius = detect_radius

func control(delta):
	if not ignore_obstacle and ($LookAhead1.is_colliding() or $LookAhead2.is_colliding()):
		speed = lerp(speed, 0, 0.1)
	else:
		speed = lerp(speed, max_speed, 0.04)
	if parent is PathFollow2D:
		parent.offset += speed * delta
		position = Vector2.ZERO
	else:
		#other movement code
		pass

func _physics_process(_delta):
	if target:
		var target_dir := (target.global_position - global_position).normalized()
		var cur_dir := Vector2.RIGHT.rotated($Turret.global_rotation)
		$Turret.global_rotation = cur_dir.linear_interpolate(target_dir, turret_speed).angle()
		
		#cos(t)>0.9
		if target_dir.dot(cur_dir) > 0.9:
			shoot(gun_shots, gun_spread, target)


func _on_DetectRadius_body_entered(body):
	target = body


func _on_DetectRadius_body_exited(body):
	if body == target:
		target = null
